import { setToken, removeToken, setUserInfo, removeUserInfo } from '@/util/auth'
import { setStore, getStore } from '@/util/store'
import { isURL, validatenull } from '@/util/validate'
 // eslint-disable-next-line
import { encryption, deepClone } from '@/util/util'
import webiste from '@/config/website'
 // eslint-disable-next-line
import { loginByUsername, getUserInfo, getMenu, getAuthMenus, getTopMenu, logout, refeshToken } from '@/api/user'

function addPath(ele, first) {
    const menu = webiste.menu;
    const propsConfig = menu.props;
    const propsDefault = {
        label: propsConfig.label || 'label',
        path: propsConfig.path || 'path',
        icon: propsConfig.icon || 'icon',
        children: propsConfig.children || 'children',
        menuId: propsConfig.menuId || 'menuId'
    }
    const menuId = ele[propsDefault.menuId];
    ele[propsDefault.menuId] = menuId;
    const icon = ele[propsDefault.icon];
    ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon;
    const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
    if (!isChild && first && !isURL(ele[propsDefault.path])) {
        ele[propsDefault.path] = ele[propsDefault.path] + '/index'
    } else {
        ele[propsDefault.children].forEach(child => {
            if (!isURL(child[propsDefault.path])) {
                child[propsDefault.path] = `${ele[propsDefault.path]}/${child[propsDefault.path] ? child[propsDefault.path] : 'index'}`
            }
            addPath(child);
        })
    }

}
const user = {
    state: {
        userInfo: getStore({ name: 'userInfo' }) || {},
        permission: {},
        roles: [],
        menu: getStore({ name: 'menu' }) || [],
        menuAll: getStore({ name: 'menuAll' }) || [],
        token: getStore({ name: 'token' }) || '',
    },
    actions: {
        //根据用户名登录
        LoginByUsername({ commit }, userForm) {
            // const user = encryption({
            //     data: userInfo,
            //     type: 'Aes',
            //     key: 'avue',
            //     param: ['useranme', 'password']
            // });
            const user = userForm
            let _that = this;
            return new Promise((resolve) => {
                loginByUsername(user.username, user.password, user.code, user.redomStr).then(res => {
                    if(res.status != 200){
                        _that._vm.$message({
                            showClose: true,
                            message: '请求失败，请联系管理员！',
                            type: 'error'
                        });
                        return
                    }
                    const data = res.data;
                    if(res.data.code != 10000){
                        _that._vm.$message({
                            showClose: true,
                            message: res.data.message,
                            type: 'error'
                        });
                        return
                    }
                    const userInfo = data.data.userInfo;
                    // if(userInfo.auth == null){
                    //     userInfo.auth = []
                    // }
                    commit('SET_PERMISSION', [])
                    commit('SET_TOKEN', userInfo.token);
                    commit('SET_USERINFO', userInfo);
                    commit('SET_ROLES', userInfo.role);
                    // commit('SET_PERMISSION', data.auth)
                    commit('DEL_ALL_TAG');
                    commit('CLEAR_LOCK');
                    resolve(userInfo);
                })
            })
        },
        //根据手机号登录
        LoginByPhone({ commit }, userInfo) {
            return new Promise((resolve) => {
                loginByUsername(userInfo.phone, userInfo.code).then(res => {
                    const data = res.data.data;
                    commit('SET_TOKEN', data);
                    commit('DEL_ALL_TAG');
                    commit('CLEAR_LOCK');
                    resolve();
                })
            })
        },
        GetUserInfo({ commit }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then((res) => {
                    const data = res.data.data;
                    commit('SET_USERINFO', data.userInfo);
                    commit('SET_ROLES', data.roles);
                    commit('SET_PERMISSION', data.permission)
                    resolve(data);
                }).catch(err => {
                    reject(err);
                })
            })
        },
        //刷新token
        RefeshToken({ state, commit }) {
            return new Promise((resolve, reject) => {
                refeshToken(state.refeshToken).then(res => {
                    const data = res.data.data;
                    commit('SET_TOKEN', data);
                    resolve(data);
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 登出
        LogOut({ commit }) {
            let _that = this
            return new Promise((resolve, reject) => {
                logout().then((res) => {
                    if(res.data.code != 10000){
                        _that.$message({
                            showClose: true,
                            message: res.data.message,
                            type: 'error'
                        });
                        return
                    }
                    commit('SET_TOKEN', '')
                    commit('SET_MENU', [])
                    commit('SET_MENU_ALL', [])
                    commit('SET_USERINFO', [])
                    commit('SET_ROLES', [])
                    commit('DEL_ALL_TAG');
                    commit('CLEAR_LOCK');
                    removeToken()
                    removeUserInfo()
                    resolve()
                    location.reload()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //注销session
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                commit('SET_MENU', [])
                commit('SET_MENU_ALL', [])
                commit('SET_USERINFO', [])
                commit('SET_ROLES', [])
                commit('DEL_ALL_TAG');
                commit('CLEAR_LOCK');
                removeToken()
                removeUserInfo()
                resolve()
            })
        },
        GetTopMenu({ commit }) {
            return new Promise(resolve => {
                getAuthMenus().then((res) => {
                    const data = res.data.data.menus || []
                    const authbtns = res.data.data.authbtns || []
                    // var menuData = []
                    // for (let i = 0; i < data.length; i++) {
                    //     if (data[i].level === 1) {
                    //         menuData.splice(-1, 0, data[i])
                    //     }
                    // }
                    commit('SET_MENU_ALL', deepClone(data))
                    commit('SET_PERMISSION', authbtns)
                    resolve(data)
                })
            })
        },
        //获取系统菜单
        GetMenu({ commit }, parentId) {
            return new Promise(resolve => {
                const data = getStore({ name: 'menuAll' }) || []
                //getAuthMenus(parentId).then((res) => {
                    //const data = res.data.data
                    // let menu = deepClone(data);
                    var menuData = [];
                    for (let i = 0; i < data.length; i++) {
                        if (data[i].id === parentId) {
                            menuData = deepClone(data[i].sub)
                        }
                    }
                    menuData.forEach(ele => {
                        addPath(ele, true);
                    })
                    // console.log('22222lijllllll', menuData)
                    commit('SET_MENU', menuData)
                    resolve(menuData)
                //})
            })
        },
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            setToken(token)
            state.token = token;
            setStore({ name: 'token', content: state.token, type: 'session' })
        },
        SET_USERINFO: (state, userInfo) => {
            state.userInfo = userInfo;
            setUserInfo(userInfo)
            setStore({ name: 'userInfo', content: state.userInfo, type: 'session' })
        },
        SET_MENU: (state, menu) => {
            state.menu = menu
            setStore({ name: 'menu', content: state.menu, type: 'session' })
        },
        SET_MENU_ALL: (state, menuAll) => {
            state.menuAll = menuAll;
            setStore({ name: 'menuAll', content: state.menuAll, type: 'session' })
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles;
        },
        SET_PERMISSION: (state, permission) => {
            state.permission = {};
            permission.forEach(ele => {
                state.permission[ele] = true;
            });
        }
    }

}
export default user